/**
 * main.js - Javascript chess library main program
 * 
 * following the module approach suggested by require.js
 * 
 * using the same: http://requirejs.org/
 *
 * http://code.google.com/p/fics-meets-html5/
 *
 * Copyright 2012 Markus Kupke
 */

requirejs.config({
	//By default load any module IDs from js/lib
	baseUrl: 'js/lib',
	//except, if the module ID starts with "app",
	//load it from the js/app directory. paths
	//config is relative to the baseUrl, and
	//never includes a ".js" extension since
	//the paths config could be for a directory.
	paths: {
		app: '../app'
	}
});

//Start the main app logic.
requirejs(['domReady','app/position','app/chessboard'],
		function   (domReady, pos, board) {
	//position & board module
	//loaded and can be used here now.
    domReady( function() {
	var chesslib = {};
	chesslib.Position_internal = pos;
	chesslib.board = board;

	var game = new chesslib.Position_internal("8/3P3p/p1N3pk/2PB1p2/3n1P2/P5P1/1q5P/3R3K w - - 0 41");
	var chessboard_div = document.getElementById("first");
	var boardnode = chesslib.board.createBoardInElement(chessboard_div);
	boardnode.chess.setFigures(game.toJSON());
	var movesArray = game.legalmoves().toString().split(',');
	var moves = {};
	movesArray.forEach(function(v){
		var from = v.slice(1,3);
		var to = v.slice(4,6);
		if ( v.length > 6 ) {
			to += '?'; 			  	
		}; 
		if(!(moves[from])) moves[from] = [];
		if(moves[from].indexOf(to)===-1) moves[from].push(to);
	});
	var func = function () {
		var fromK = Object.keys(boardnode.chess.move);
		if (fromK.length > 2) throw new Error ("move property of board malformed");
		var fromS = fromK[0].length > 2 ? fromK[1]:fromK[0];
		var toS = boardnode.chess.move[fromS];
		var from = ("abcdefgh".indexOf(fromS[0]) + 1) + (parseInt(fromS[1]) + 1) * 10; 
		var to = ("abcdefgh".indexOf(toS[0]) + 1) + (parseInt(toS[1]) + 1) * 10; 
		var userMoveArray = game.legalmoves().filter(function(m){return (m.from === from && m.to === to)});
		if (userMoveArray.length === 0) throw new Error("Fatal: this should never happen. The user was able to make an illegal move");
		if (userMoveArray.length === 1) {
			var userMove = userMoveArray[0];
		} else {
			userMoveArray = userMoveArray.filter(function(m){return (m.changetofigure.toUpperCase() === boardnode.chess.move.promotion )});
			var userMove = userMoveArray[0];
		};
		game = game.apply_move(userMove);
		boardnode.chess.setFigures(game.toJSON());
		var movesArray = game.legalmoves().toString().split(',');
		moves = {};
		movesArray.forEach(function(v){
			var from = v.slice(1,3);
			var to = v.slice(4,6);
			if ( v.length > 6 ) {
				to += '?'; 			  	
			}; 
			if(!(moves[from])) moves[from] = [];
			if(moves[from].indexOf(to)===-1) moves[from].push(to);
		});
		boardnode.chess.setPossibleMoves(moves, func);		
	};
	boardnode.chess.setPossibleMoves(moves, func);		
})
});
